package cn.walls1717.wallsmall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.walls1717.wallsmall.common.pojo.to.SkuReductionTO;
import cn.walls1717.wallsmall.common.pojo.to.SpuBoundTO;
import cn.walls1717.wallsmall.common.pojo.to.es.SkuEsModel;
import cn.walls1717.wallsmall.common.utils.PageUtils;
import cn.walls1717.wallsmall.common.utils.Query;
import cn.walls1717.wallsmall.common.utils.R;
import cn.walls1717.wallsmall.product.dao.SpuInfoDao;
import cn.walls1717.wallsmall.product.entity.*;
import cn.walls1717.wallsmall.product.feign.CouponFeignService;
import cn.walls1717.wallsmall.product.feign.SearchFeignService;
import cn.walls1717.wallsmall.product.feign.WareFeignService;
import cn.walls1717.wallsmall.product.service.*;
import cn.walls1717.wallsmall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.walls1717.wallsmall.common.constant.product.ProductStatusEnum.SPU_UP;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;

    /**
     * 条件分页查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils listPagesByConditions(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> lqw = new LambdaQueryWrapper<>();
        String key = (String)params.get("key");
        // 查询条件id、name
        if (!StrUtil.isEmpty(key)) {
            lqw.and(w -> w.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key));
        }
        // 查询条件catelogId
        String catalogId = (String)params.get("catelogId");
        if (!StrUtil.isEmpty(catalogId) && !StrUtil.equals(catalogId, "0")) {
            lqw.eq(SpuInfoEntity::getCatalogId, catalogId);
        }
        // 查询条件brandId
        String brandId = (String)params.get("brandId");
        if (!StrUtil.isEmpty(brandId) && !StrUtil.equals(brandId, "0")) {
            lqw.eq(SpuInfoEntity::getBrandId, brandId);
        }
        // 查询条件publicStatus
        String status = (String)params.get("status");
        if (!StrUtil.isEmpty(status)) {
            lqw.eq(SpuInfoEntity::getPublishStatus, status);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), lqw);
        return new PageUtils(page);
    }

    /**
     * 保存商品的所有信息 操作的表有: 1.pms_spu_info 2.pms_spu_info_desc 3.pms_spu_images 4.pms_product_attr_value 5.sms_spu_bounds
     * 6.pms_sku_info 7.pms_sku_images 8.pms_sku_sale_attr_value 9.sms_sku_ladder 10.sms_sku_full_reduction
     * 11.sms_member_price
     *
     * @param spuSaveVO 商品保存所用参数
     */
    @Override
    // @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void saveProduct(SpuSaveVO spuSaveVO) {
        // 保存spu基本信息 pms_spu_info
        // pms_spu_info
        SpuInfoEntity spu = new SpuInfoEntity();
        BeanUtil.copyProperties(spuSaveVO, spu);
        spu.setCreateTime(new Date());
        spu.setUpdateTime(new Date());
        // 保存psm_spu_info
        save(spu);

        // 保存spu图片描述 pms_spu_info_desc
        List<String> descriptions = spuSaveVO.getDecript();
        // pms_spu_info_desc
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        Long spuId = spu.getId();
        spuInfoDesc.setSpuId(spuId);
        spuInfoDesc.setDecript(StrUtil.join(",", descriptions));
        // 保存pms_spu_info_desc
        spuInfoDescService.save(spuInfoDesc);

        // 保存spu图片 pms_spu_images
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveBatchSpuImages(spuId, images);

        // 保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValues = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            Long attrId = baseAttr.getAttrId();
            productAttrValue.setAttrId(attrId);
            AttrEntity attr = attrService.getById(attrId);
            productAttrValue.setAttrName(attr.getAttrName());
            productAttrValue.setAttrValue(baseAttr.getAttrValues());
            productAttrValue.setQuickShow(baseAttr.getShowDesc());
            productAttrValue.setSpuId(spuId);
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValues);
        // 保存spu积分信息 wallsmall-sms -> sms_spu_bounds
        Bounds bounds = spuSaveVO.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtil.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 没有获取到sku则不需要保存
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus == null || skus.size() == 0) {
            return;
        }
        // 保存sku
        skus.forEach(sku -> {
            // 1.sku基本信息 pms_sku_info
            String defaultImg = "";
            // 获取默认图片 defaultImg为1表示默认图片
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImg = image.getImgUrl();
                }
            }
            SkuInfoEntity skuInfo = new SkuInfoEntity();
            BeanUtil.copyProperties(sku, skuInfo);
            skuInfo.setBrandId(spu.getBrandId());
            skuInfo.setCatalogId(spu.getCatalogId());
            skuInfo.setSaleCount(0L);
            skuInfo.setSpuId(spuId);
            skuInfo.setSkuDefaultImg(defaultImg);
            skuInfoService.save(skuInfo);
            // 2.sku图片 pms_sku_images
            Long skuId = skuInfo.getSkuId();
            List<SkuImagesEntity> skuImages = sku.getImages().stream().map(img -> {
                SkuImagesEntity skuImage = new SkuImagesEntity();
                skuImage.setSkuId(skuId);
                skuImage.setImgUrl(img.getImgUrl());
                skuImage.setDefaultImg(img.getDefaultImg());
                return skuImage;
            }).filter(img -> !StrUtil.isEmpty(img.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImages);
            // 3.sku销售属性 pms_sku_sale_attr_value
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValues = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                BeanUtil.copyProperties(attr, skuSaleAttrValue);
                skuSaleAttrValue.setSkuId(skuId);
                return skuSaleAttrValue;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValues);
            // 4.sku优惠、满减等信息 wallsmall-sms -> sms_sku_ladder、sms_sku_full_reduction、sms_member_price
            SkuReductionTO skuReductionTO = new SkuReductionTO();
            BeanUtil.copyProperties(sku, skuReductionTO);
            skuReductionTO.setSkuId(skuId);
            if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                if (r1.getCode() != 0) {
                    log.error("远程保存spu优惠信息失败");
                }
            }
        });
    }

    /**
     * 修改商品发布状态[0 - 下架，1 - 上架]
     *
     * @param spuId spuId
     */
    @Override
    public void updatePublishStatus(Long spuId) {
        // 封装数据为SkuEsModel.Attrs集合
        List<ProductAttrValueEntity> productAttrValues = productAttrValueService.listProductAttrValuesBySpuId(spuId);
        List<Long> attrIds =
            productAttrValues.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 拿到检索属性(search_type:1)的attrId
        List<Long> searchAttrIds = attrService.listSearchAttrIdsByAttIds(attrIds);
        HashSet<Long> searchAttrIdsSet = new HashSet<>(searchAttrIds);
        // 将检索属性封装为SkuEsModel.Attrs
        List<SkuEsModel.Attrs> attrs = productAttrValues.stream()
            // 过滤掉不是检索属性的属性
            .filter(productAttrValue -> searchAttrIdsSet.contains(productAttrValue.getAttrId()))
            .map(productAttrValue -> {
                SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                BeanUtil.copyProperties(productAttrValue, attr);
                return attr;
            }).collect(Collectors.toList());

        List<SkuInfoEntity> skus = skuInfoService.listSkusBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> skuHasStockMap = null;
        try {
            List<SkuHasStockVO> skuHasStockVOS = wareFeignService.getHasStock(skuIds);
            log.info("库存远程调用结果 -> {}", skuHasStockVOS.toString());
            skuHasStockMap =
                skuHasStockVOS.stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));
        } catch (Exception e) {
            log.error("库存远程调用出现异常 -> {}", e.toString());
        }

        // 封装数据为SkuEsModel
        Map<Long, Boolean> finalSkuHasStockMap = skuHasStockMap;
        List<SkuEsModel> skuEsModels = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            // 设置基本信息
            BeanUtil.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // 远程调用查询是否有库存
            if (finalSkuHasStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalSkuHasStockMap.get(sku.getSkuId()));
            }

            // 热度评分
            skuEsModel.setHotScore(0L);

            // 设置品牌信息
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            // 设置分类信息
            CategoryEntity catalog = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(catalog.getName());

            // 设置检索属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        // 写入ES
        R r = searchFeignService.productStatusUp(skuEsModels);
        log.info("ES远程调用结果 -> {}", r.getCode());
        if (r.getCode() == 0) {
            // 商品上架成功修改spu上架状态
            baseMapper.updateStatusBySpuId(spuId, SPU_UP.getCode());
        }
        // TODO 重复调用，接口幂等性

    }

    /**
     * 根据skuId获取spu信息
     *
     * @param skuId skuId
     * @return sku信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        return getById(skuInfo.getSpuId());
    }
}